package com.smmisia.article.listen;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.smmisia.article.dto.request.FollowRequest;
import com.smmisia.article.entity.Concern;
import com.smmisia.article.entity.Follow;
import com.smmisia.article.listen.message.FollowMessage;
import com.smmisia.article.mapper.ConcernMapper;
import com.smmisia.article.mapper.FollowMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.function.Consumer;

@Slf4j
@Component
public class FollowsListener {

    @Autowired
    private FollowMapper followMapper;

    @Autowired
    private ConcernMapper concernMapper;

    @Bean
    @Transactional(rollbackFor = Exception.class)
    Consumer<Message<FollowMessage>> follows() {
        return msg -> {
            FollowMessage request = msg.getPayload();
            log.info("收到取消关注消息:{}", JSON.toJSONString(request));
            LambdaQueryWrapper<Follow> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Follow::getUserId, request.getUserId());
            wrapper.eq(Follow::getFollowUserId, request.getTargetId());
            followMapper.delete(wrapper);
            LambdaQueryWrapper<Concern> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Concern::getUserId, request.getTargetId());
            queryWrapper.eq(Concern::getConcernUserId, request.getUserId());
            concernMapper.delete(queryWrapper);
        };
    }
}
